package a_erfenchazhao.lianxiti;

/**
 * @ClassName SouSuoXuanZhuanPaiXuShuZu
 * @Description
 * @Author Zhang Li Tao
 * @Date 2024/3/18
 * @Version 1.0
 **/
public class SouSuoXuanZhuanPaiXuShuZu {
    public static void main(String[] args) {
        /**
         *
         * nums = [4,5,6,7,1,2,3], target = 1
         */
        int[] array = {1};
        int target = 0;

        System.out.println(search(array, target));
    }

    public static int search(int[] nums, int target) {
        int leftIndex = 0;
        int rightIndex = nums.length - 1;

        if (nums.length == 1) {
            return nums[0] == target ? 0 : -1;
        }

        if (target == nums[0]) {
            return 0;
        }

        while (leftIndex <= rightIndex) {
            int middleIndex = (leftIndex + rightIndex) >>> 1;

            if (target == nums[middleIndex]) {
                return middleIndex;
            }

            if (target < nums[middleIndex]) {
                if (target > nums[0]) {
                    rightIndex = middleIndex - 1;
                } else {
                    leftIndex = middleIndex + 1;
                    if (target == nums[leftIndex]){
                        return leftIndex;
                    }
                }
            } else { // 右半部分
                leftIndex = middleIndex + 1;
            }
        }
        return -1;
    }
}
